import type { Ref } from 'vue'
import { onMounted, onUnmounted, ref } from 'vue'

export function useCountDown(countDown: number) {
  const time = ref(countDown)
  const idle = ref(false)
  let timer: any
  const start = () => {
    if (!idle.value)
      idle.value = true
    time.value--
    if (time.value >= 1) {
      timer = setTimeout(start, 1000)
    }
    else {
      idle.value = false
      time.value = countDown
    }
  }
  onUnmounted(() => {
    clearTimeout(timer)
  })
  return {
    idle,
    time,
    start,
  }
}

interface UseRefreshLoad<T extends IRes<any>> {
  list: Ref<T['Datas']>
  loading: Ref<boolean>
  finished: Ref<boolean>
  refreshing: Ref<boolean>
  onRefresh: (param?: Record<string, any>) => void
  onLoad: () => void
}

export function useRefreshLoad<T extends IRes<any>>(server: (params?: any) => Promise<T>, options?: Record<string, any>): UseRefreshLoad<T> {
  const defaultOptions = {
    pageIndex: 0,
    pageSize: 4,
  }
  const { domRef, ...restOptions } = options || {}
  if (restOptions)
    Object.assign(defaultOptions, restOptions)
  const params = ref({ ...defaultOptions })
  const list = ref<T['Datas']>([] as T['Datas'])
  const loading = ref(false)
  const finished = ref(false)
  const refreshing = ref(false)

  const onLoad = async () => {
    try {
      loading.value = true
      if (refreshing.value) {
        list.value = []
        refreshing.value = false
      }
      const res = await server(params.value)
      if (Array.isArray(res.Datas)) {
        list.value.push(...res.Datas)
      }
      loading.value = false
      if (list.value.length >= res.Total) {
        finished.value = true
      }
      else {
        params.value.pageIndex += 1
      }
    }
    catch (error) {
      console.log(error)
    }
  }

  const onRefresh = (param = {}) => {
    // 清空列表数据
    list.value = []
    params.value = { ...defaultOptions, ...param }
    finished.value = false
    // 重新加载数据
    // 将 loading 设置为 true，表示处于加载状态
    loading.value = true
    onLoad()
  }

  const scrollHandler = () => {
    if (loading.value || finished.value)
      return
    if (window.innerHeight + window.scrollY >= domRef.value.offsetHeight) {
      onLoad()
    }
  }

  onMounted(() => {
    scrollHandler()
    window.addEventListener('scroll', scrollHandler)
  })
  onUnmounted(() => {
    window.removeEventListener('scroll', scrollHandler)
  })

  return {
    list,
    loading,
    finished,
    refreshing,
    onRefresh,
    onLoad,
  }
}
